<template>
  <div class="my-answers-container">
    <div class="header-section">
      <h2>我的测试</h2>
      <el-button 
        type="primary" 
        size="mini" 
        icon="el-icon-refresh" 
        @click="refreshTests" 
        :loading="refreshing">
        刷新
      </el-button>
    </div>
    
    <el-tabs v-model="activeTab" type="card" class="compact-tabs">
      <el-tab-pane label="未截止测试" name="pending">
        <div class="test-list" v-loading="loading">
          <div v-if="pendingTests.length === 0" class="empty-state">
            <el-empty description="暂无未截止的测试"></el-empty>
          </div>
          
          <div v-if="pendingTests.length !==0" class="hierarchical-selection">
            <el-collapse accordion>
              <el-collapse-item v-for="test in pendingTests" :key="test.id">
                <template slot="title">
                  <div class="test-header">
                    <div class="test-info">
                      <span class="test-purpose">{{ test.purpose }}</span>
                      <span class="test-class">({{ test.className }})</span>
                    </div>
                    <div class="test-meta">
                      <span class="meta-item"><i class="el-icon-date"></i> {{ formatDate(test.endTime) }}</span>
                      <span class="meta-item"><i class="el-icon-trophy"></i> {{ test.score }}分</span>
                      <el-tag type="warning" size="mini" v-if="isNearDeadline(test.endTime)">即将截止</el-tag>
                    </div>
                  </div>
                </template>
                
                <div class="test-detail-panel">
                  <div class="test-progress" v-if="test.savedProgress">
                    <span>已完成进度: {{ test.progress }}%</span>
                    <el-progress :percentage="test.progress" :stroke-width="8"></el-progress>
                  </div>
                  
                  <div class="test-actions">
                    <el-button type="primary" @click="viewTestResult(test.id)" size="mini">继续答题</el-button>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="已截止测试" name="completed">
        <div class="test-list" v-loading="loading">
          <div v-if="completedTests.length === 0" class="empty-state">
            <el-empty description="暂无已截止的测试"></el-empty>
          </div>
          
          <div v-if="completedTests.length !==0" class="hierarchical-selection">
            <el-collapse accordion>
              <el-collapse-item v-for="test in completedTests" :key="test.id">
                <template slot="title">
                  <div class="test-header">
                    <div class="test-info">
                      <span class="test-purpose">{{ test.purpose }}</span>
                      <span class="test-class">({{ test.className }})</span>
                    </div>
                    <div class="test-meta">
                      <span class="meta-item"><i class="el-icon-time"></i> {{ formatDate(test.endTime) }}</span>
                      <span class="meta-item"><i class="el-icon-trophy"></i> {{ test.score }}分</span>
                      <el-tag type="success" size="mini" v-if="test.hasResults">已批阅</el-tag>
                      <el-tag size="mini" v-else>待批阅</el-tag>
                    </div>
                  </div>
                </template>
                
                <div class="test-detail-panel">
                  <div class="test-progress" v-if="test.progress">
                    <span>完成进度: {{ test.progress }}%</span>
                    <el-progress :percentage="test.progress" :stroke-width="8"></el-progress>
                  </div>
                  
                  <div class="test-actions">
                    <el-button type="primary" @click="viewTestResult(test.id)" size="mini">查看结果</el-button>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: 'MyAnswers',
  data() {
    return {
      activeTab: 'pending',
      loading: false,
      refreshing: false,
      pendingTests: [],
      completedTests: [],
      userId:'',
      testlist:[],
      componentKey: 0,
      _dataLoaded: false
    }
  },
  created() {
    // 尝试从Vuex获取用户ID
    this.getUserId();
    // 初始加载只执行一次
    if (!this._dataLoaded) {
      this.fetchMyTests();
      this._dataLoaded = true;
    }
  },
  
  // 当页面被激活时触发（使用keep-alive时）
  activated() {
    // 仅检查测试提交状态，不自动刷新数据
    this.checkTestSubmission();
  },
  methods: {
    // 获取用户ID的方法
    getUserId() {
      try {
        // 首先尝试从Vuex获取
        if (this.$store && this.$store.state && this.$store.state.userInfo && this.$store.state.userInfo.userId) {
          this.userId = this.$store.state.userInfo.userId;
        } 
        // 如果从Vuex获取失败，尝试从localStorage获取
        else if (localStorage.getItem('userInfo')) {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          if (userInfo && userInfo.userId) {
            this.userId = userInfo.userId;
          }
        }
        
        // 如果仍然没有userId，尝试从URL参数获取
        if (!this.userId && this.$route.params.id) {
          this.userId = parseInt(this.$route.params.id);
        }
        
        // 如果所有方法都失败，记录错误
        if (!this.userId) {
          console.error('无法获取用户ID, 数据加载可能会失败');
        } else {
          console.log('成功获取用户ID:', this.userId);
        }
      } catch (error) {
        console.error('获取用户ID时出错:', error);
      }
    },
    async fetchMyTests() {
      console.log('开始获取测试数据 - userId:', this.userId);
      if (!this.userId) {
        console.error('用户ID不存在，无法获取数据');
        this.$message.error('无法获取用户信息，请重新登录');
        return;
      }
      
      this.loading = true;
      
      // 清空原有数据，避免重复添加
      this.pendingTests = [];
      this.completedTests = [];
      
      // 创建数据容器Map，用于去重
      const pendingMap = new Map();
      const completedMap = new Map();
      
      try {
        // 调用API获取最新数据
        const studentId = this.userId;
        console.log('发送请求获取测试数据, studentId:', studentId);
        const response = await this.$http.get('/result/student', { params: { studentId } });
        console.log('API响应:', response);
        
        const data = response.data;
        if (!data || data.length === 0) {
          console.log('API返回的数据为空');
          this.loading = false;
          return;
        }
        
        console.log('成功获取测试数据, 班级数量:', data.length);
        
        // 处理新的三元数组结构：班级 -> 测试 -> 答题记录
        data.forEach(classInfo => {
          const className = classInfo.className;
          const classId = classInfo.classId;
          console.log(`处理班级: ${className} (ID: ${classId})`);
          
          // 遍历该班级的所有测试
          classInfo.tests.forEach(testInfo => {
            const testName = testInfo.testName;
            const results = testInfo.results;
            
            if (!results || results.length === 0) {
              console.log(`测试 ${testName} 没有答题记录，跳过`);
              return;
            }
            
            console.log(`处理测试: ${testName}, 题目数量: ${results.length}`);
            
            // 从第一条记录获取基本信息
            const firstResult = results[0];
            
            // 获取题目数量和分数
            const questionCount = results.length;
            const totalScore = results.reduce((sum, r) => sum + (r.score || 0), 0);
            
            // 计算是否已截止（根据截止时间）
            const deadline = new Date(firstResult.endTime);
            const now = new Date();
            const isExpired = now > deadline;
            
            // 检查是否已提交（isCommit为1）
            const isSubmitted = results.some(result => result.isCommit === 1);
            
            // 基于isCommit字段判断状态，如果已提交则标记为已完成
            const status = isSubmitted ? 'completed' : (isExpired ? 'completed' : 'pending');
            
            const test = {
              id: testName, // 使用testName作为唯一标识
              purpose: testName, // 使用testName作为显示名称
              endTime: firstResult.endTime,
              score: totalScore,
              questionCount,
              status,
              questions: results,
              progress: 0,
              savedProgress: false,
              hasResults: false, // 初始化为false
              className: className, // 添加班级信息
              classId: classId
            };
            
            // 检查是否已批阅（结果中至少有一个评分或评论）
            test.hasResults = results.some(question => 
              (question.score !== null && question.score !== undefined && question.score > 0) ||
              (question.comment !== null && question.comment !== undefined && question.comment.trim() !== '')
            );
            
            // 从localStorage获取保存的进度（如果有）
            try {
              const savedAnswers = localStorage.getItem(`test_answers_${test.id}`);
              if (savedAnswers) {
                const answersObj = JSON.parse(savedAnswers);
                // 计算进度
                test.progress = this.calculateProgress(answersObj, questionCount);
                test.savedProgress = test.progress > 0;
              }
            } catch (e) {
              console.error('读取保存的进度出错:', e);
            }
            
            // 根据状态添加到相应数组
            if (status === 'completed') {
              // 确保没有重复添加
              if (!completedMap.has(test.id)) {
                completedMap.set(test.id, test);
                this.completedTests.push(test);
              }
            } else {
              // 确保没有重复添加
              if (!pendingMap.has(test.id)) {
                pendingMap.set(test.id, test);
                this.pendingTests.push(test);
              }
            }
          });
        });
        
        // 合并测试列表，但保证不重复
        this.testlist = [...this.pendingTests, ...this.completedTests];
        console.log('处理完成，待完成测试：', this.pendingTests.length, '已完成测试：', this.completedTests.length);
      } catch (error) {
        console.error('获取测试列表出错:', error);
        this.$message.error('获取测试列表失败，请稍后再试');
      } finally {
        this.loading = false;
      }
    },
    calculateProgress(answers, questionCount) {
      if (!answers) return 0;
      
      const completedQuestions = Object.values(answers).filter(answer => answer && answer.trim() !== '').length;
      return Math.round((completedQuestions / questionCount) * 100);
    },
    formatDate(dateString) {
      if (!dateString) return '未设置';
      
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    isNearDeadline(deadline) {
      if (!deadline) return false;
      
      const deadlineDate = new Date(deadline);
      const now = new Date();
      const timeDiff = deadlineDate - now;
      
      // 如果截止时间在1小时内，则认为即将截止
      return timeDiff > 0 && timeDiff < 1 * 60 * 60 * 1000;
    },
    viewTestResult(testId) {
      // 查找当前测试对象
      const testItem = this.testlist.find(t => t.id === testId);
      
      if (testItem) {
        // 将测试基本信息保存到sessionStorage
        sessionStorage.setItem('current_test_info', JSON.stringify({
          id: testItem.id,
          purpose: testItem.purpose,
          totalScore: testItem.score,
          questionCount: testItem.questionCount || 0,
          endTime: testItem.endTime,
          status: testItem.status,
          className: testItem.className,
          classId: testItem.classId
        }));
        
        // 将测试详情保存到sessionStorage
        if (testItem.questions) {
          sessionStorage.setItem('current_test_details', JSON.stringify(testItem.questions));
        }
      }
      
      // 跳转到测试详情页面
      this.$router.push({
        name: 'TestDetail',
        params: { id: testId }
      });
    },
    
    // 刷新测试数据
    async refreshTests() {
      this.refreshing = true;
      try {
        // 清空现有数据
        this.pendingTests = [];
        this.completedTests = [];
        
        // 获取最新数据
        await this.fetchMyTests();
        this.$message.success('数据已更新');
      } catch (error) {
        console.error('刷新数据失败:', error);
        this.$message.error('刷新数据失败，请稍后再试');
      } finally {
        this.refreshing = false;
      }
    },
    // 检查是否刚从TestDetail提交了测试
    checkTestSubmission() {
      const testJustSubmitted = localStorage.getItem('test_just_submitted');
      if (testJustSubmitted === 'true') {
        console.log('检测到刚刚提交了测试，强制刷新数据');
        
        // 清除标记
        localStorage.removeItem('test_just_submitted');
        
        // 强制刷新数据
        this.refreshTests();
        
        // 显示消息
        this.$message.success('测试已提交，数据已更新');
      }
    },
  }
}
</script>

<style scoped>
.my-answers-container {
  padding: 8px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.header-section h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.hierarchical-selection {
  margin-top: 6px;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 6px 8px;
}

.test-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.test-purpose {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.test-class {
  font-size: 13px;
  color: #909399;
}

.test-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  color: #606266;
}

.meta-item {
  font-size: 13px;
}

.meta-item i {
  margin-right: 3px;
}

.test-detail-panel {
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.test-progress {
  margin-bottom: 6px;
  font-size: 13px;
}

.test-actions {
  margin-top: 6px;
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  padding: 15px;
  text-align: center;
}

.test-list {
  margin-top: 6px;
}

/* Element UI 组件紧凑样式 */
:deep(.el-tabs__header) {
  margin-bottom: 6px;
}

:deep(.el-tab-pane) {
  padding: 0;
}

:deep(.el-collapse-item__header) {
  padding: 6px 8px;
  font-size: 15px;
  min-height: 36px;
}

:deep(.el-collapse-item__content) {
  padding: 0;
}

:deep(.el-button--mini) {
  padding: 4px 10px;
  font-size: 13px;
  height: 28px;
}

:deep(.el-tag--mini) {
  height: 20px;
  line-height: 20px;
  padding: 0 5px;
  font-size: 12px;
}

:deep(.el-progress) {
  margin: 2px 0;
}

:deep(.el-progress__text) {
  font-size: 13px;
}

:deep(.el-empty) {
  padding: 15px 0;
}

:deep(.el-empty__description) {
  font-size: 14px;
}

:deep(.el-tabs__item) {
  padding: 8px 16px;
  font-size: 15px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item) {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 6px;
}

:deep(.el-collapse-item:last-child) {
  margin-bottom: 0;
}
</style>
